package com.alawn.framework.core.web.model;

import com.alawn.framework.core.domain.BaseEntity;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import java.util.List;
import java.util.Map;

public abstract class PageModel<T extends BaseEntity> extends LazyDataModel<T> {
    private static final long serialVersionUID = 2957926997919683676L;

    protected abstract BaseMapper<T> getEntityMapper();

    @Override
    public T getRowData(String rowKey) {
        return getEntityMapper().selectById(Long.valueOf(rowKey));
    }

    @Override
    public List<T> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
        IPage<T> page = getEntityMapper().selectPage(new Page<T>(getPage(first, pageSize), pageSize),
                new QueryWrapper<T>().allEq(filters).orderBy(StringUtils.isNotBlank(sortField),
                        SortOrder.ASCENDING.equals(sortOrder), sortField));
        this.setRowCount((int) page.getTotal());
        return page.getRecords();
    }

    @Override
    public void setRowIndex(int rowIndex) {
        super.setRowIndex((getPageSize() == 0) ? -1 : rowIndex);
    }

    private int getPage(int first, int pageSize) {
        int pageNum = (pageSize > 0) ? (first / pageSize) : 0;
        return pageNum + 1;
    }
}
